package com.aio;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

public class ServerCompletionHandler implements CompletionHandler<AsynchronousSocketChannel,Server> {

	@Override
	public void completed(AsynchronousSocketChannel asc, Server attachment) {
		//当有一个客户端输入的时候，直接调用Server的accept方法，这样反复执行下去，保证多个客户端可以阻塞
		attachment.assc.accept(attachment, this);
		read(asc);
	}
	@Override
	public void failed(Throwable exc, Server attachment) {
		exc.printStackTrace();
	}
	/**
	 * 读取数据
	 * @param asc
	 */
	private void read(AsynchronousSocketChannel asc) {
		//读取数据
		ByteBuffer buf = ByteBuffer.allocate(1024);
		asc.read(buf, buf, new CompletionHandler<Integer, ByteBuffer>() {
			@Override
			public void completed(Integer result, ByteBuffer attachment) {
				//进行数据读取之前，进行复位操作
				attachment.flip();
				//输出读取的字节数
				System.out.println("服务端，收到客户端的数据长度为："+result);
				//获取读取的数据
				String resultData = new String(attachment.array()).trim();
				System.out.println("服务端，收到客户端数据为："+resultData);
				String response = "服务端响应，收到客户端发送的数据"+resultData;
				write(asc,response);
			}

			@Override
			public void failed(Throwable exc, ByteBuffer attachment) {
				exc.printStackTrace();
			}
		});
	}
	/**
	 * 写数据
	 * @param response
	 */
	private void write(AsynchronousSocketChannel asc, String response) {
		try {
			ByteBuffer buf = ByteBuffer.allocate(1024);
			buf.put(response.getBytes());
			buf.flip();
			asc.write(buf);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
